package com.gesonet.common.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


@SuppressWarnings("deprecation")
public class HttpClientUtils {

	private final static Logger LOG = LoggerFactory
			.getLogger(HttpClientUtils.class);

	public static String sendGet(String httpURLString) throws IOException {

		LOG.info("getHttpRespData url=" + httpURLString);
		HttpURLConnection conn = null;
		BufferedReader reader = null;
		String respData = StringUtils.EMPTY;
		String dataline = StringUtils.EMPTY;
		try {
			URL url = new URL(httpURLString);
			conn = (HttpURLConnection) url.openConnection();
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setRequestMethod("GET");
			conn.setUseCaches(false);
			conn.setReadTimeout(60000);
			conn.setConnectTimeout(60000);
			conn.setRequestProperty("ContentType", "text/html; charset=UTF-8");
			// conn.setRequestProperty("Itv-userToken",
			// "QDEwMDY1YWFiYTdkYzVhYmZjOjE6MTM3NzY4NzM1MzoyMjExMjk1OTFkNmU3NjQyOWQ0MDZiZThiOGRjNDNmNw==");
			int respCode = conn.getResponseCode();
			if (respCode == HttpURLConnection.HTTP_OK) {
				reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
				while ((dataline = reader.readLine()) != null) {
					respData += dataline.trim();
				}
			}
		} finally {
			if (reader != null) {
				try {
					reader.close();
					reader = null;
				} catch (IOException e) {
					LOG.error("请求地址{}失败", httpURLString);
					e.printStackTrace();
				}
			}
			if (conn != null) {
				conn.disconnect();
				conn = null;
			}
		}
		return respData;
	}

	/**
	 * 向指定 URL 发送POST方法的请求
	 * @param url 发送请求的 URL
	 * @param params 请求参数
	 * @return 所代表远程资源的响应结果
	 */
	public static String sendPost(String url, Map<String, Object> params) {
		BufferedReader in = null;
		String result = "";
		OutputStreamWriter out = null;
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
//			conn.setRequestProperty("user-agent",
//					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new OutputStreamWriter(conn.getOutputStream(),"UTF-8");
			// 发送请求参数
			StringBuffer sb = new StringBuffer();
			if (params != null) {
				for (Entry<String, Object> e : params.entrySet()) {
					sb.append(e.getKey());
					sb.append("=");
					sb.append(e.getValue());
					sb.append("&");
				}
				sb.substring(0, sb.length() - 1);
			}
			out.write(sb.toString());
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			LOG.error("发送 POST 请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 校验url是否可达
	 * @param url
	 * @return
	 */
	public static boolean exists(String url) {
		try {
			// 设置此类是否应该自动执行 HTTP 重定向（响应代码为 3xx 的请求）。
			HttpURLConnection.setFollowRedirects(false);
			// 到 URL 所引用的远程对象的连接
			HttpURLConnection con = (HttpURLConnection) new URL(url)
					.openConnection();
			/*
			 * 设置 URL 请求的方法， GET POST HEAD OPTIONS PUT DELETE TRACE
			 * 以上方法之一是合法的，具体取决于协议的限制。
			 */
			con.setRequestMethod("HEAD");
			// 从 HTTP 响应消息获取状态码
			return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	@SuppressWarnings({ "resource" })
	public static String methodPost(String url,Map<String, String> params) throws Exception {
		DefaultHttpClient httpclient = new DefaultHttpClient();
		// // 代理的设置
		// HttpHost proxy = new HttpHost("10.60.8.20", 8080);
		// httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
		// proxy);
		// 目标地址
		HttpPost httppost = new HttpPost(url);
		LOG.debug("请求: " + httppost.getRequestLine());
		// post 参数 传递
		List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
		for (Map.Entry<String, String> entry : params.entrySet()) {
			nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); // 参数
		}
		httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); // 设置参数给Post
		// 执行
		HttpResponse response = httpclient.execute(httppost);
		HttpEntity entity = response.getEntity();
		LOG.debug(response.getStatusLine()+"");
		if (entity != null) {
			LOG.debug("Response content length: " + entity.getContentLength());
		}
		// 显示结果
		BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
		String line = null;
		while ((line = reader.readLine()) != null) {
			LOG.debug(line);
		}
		if (entity != null) {
			entity.consumeContent();
		}
		return null;

	}
	
	public static void main(String[] args) throws Exception {

	}

}
